//动态表单设计器

import React, {useState} from 'react';
import {Button, Form, Input, message, PageHeader} from 'antd';
import {createFromIconfontCN,ToolOutlined,DeleteOutlined} from '@ant-design/icons';
import LayoutProperty from "./propertyForm/layoutProperty";
import InputProperty from "./propertyForm/inputProperty";
import TitleProperty from "./propertyForm/titleProperty";

import { Link, Route, Switch } from "react-router-dom";

const ROW_TYPE=1;   //行类型
const COL_TYPE=2;   //列类型

export default function Dynamic_Form_Designer2(prop) {
    const Category = () => (
        <div>
            <h2>Category</h2>
        </div>
    );
    const  [form] = Form.useForm();
    /**flexGrow ：flex grow 值**/
    const getRowLayoutStyle=(flexGrow,justifyContentVal,alignItemsVal)=>{
        return {flex: flexGrow+" 1 auto",
            justifyContent:justifyContentVal,
            alignContent:alignItemsVal,
            alignItems:"stretch",
            // border: "1px solid #cccccc",
            paddingTop:"1em",paddingLeft:"0.3em",paddingRight:"1em",paddingBottom:"1em",
            margin:"0.5em",backgroundColor:"RGB(172,216,230)",boxSizing: "border-box",
            display:"flex",
            flexDirection:"row",
            position:"relative"
        }
     }
    const getColLayoutStyle=(flexGrow,justifyContentVal,alignItemsVal)=>{
        return {
            // border: "1px solid #cccccc",
            flex: flexGrow+" 1 auto",
            justifyContent:justifyContentVal,
            alignContent:alignItemsVal,
            alignItems:"stretch",
            paddingTop:"1em",paddingLeft:"0.3em",paddingRight:"1em",paddingBottom:"1.5em",
            margin:"0.3em",backgroundColor:"RGB(135,206,235)",
            display: "flex",
            flexDirection:"column",
            position:"relative"
        }
    }
    //标题样式
    const getTitleStyle=()=>{
        return {
             border: "1px dashed #000000",
             //height: "1em"
        }
    }
    const rowTool={
        display: "flex",
        flexDirection: "column",
        boxSizing: "border-box",
        // border: "2px solid #999999"
    }

    const rowEditTool={
        position:"absolute",
        top: 2,
        right: 1
    }

    const colEditTool={
        position:"absolute",
        top: 2,
        right: 1
    }

    const rowRemoveTool={
        position:"absolute",
        top: 50,
        right: 50
    }

    const colRemoveTool={
        position:"absolute",
        top: 2,
        right: 20
    }

    const colTool={
        display: "flex",
        flexDirection: "row",
        boxSizing: "border-box",
        // border: "2px solid #999999",
        justifyContent:"flex-end"
    }

    let _children=[];
    //id,key,parentId,name,layoutType,flexGrow,children,colSpan,showVale
    let layoutTreeNood1 = new LayoutTreeNode("1",1,"0","row1",1,1,[],"center");  //布局树
    let layoutTreeNood2 = new LayoutTreeNode("2",2,"0","row2",1,1,[]);  //布局树
    let layoutTreeNood3 = new LayoutTreeNode("3",3,"0","row3",1,2,[]);  //布局树
    let layoutTreeRoot = new LayoutTreeNode("0",0,"-1","root",2,1,_children);  //布局树
    _children.push(layoutTreeNood1);
    // _children.push(layoutTreeNood2);
    // _children.push(layoutTreeNood3);
    // id,key,parentId,name,layoutType,flexGrow,children
    // let layoutTreeNood1_col1 = new LayoutTreeNode("11",11,"1","col11",2,1,[],6);  //布局树
    // let layoutTreeNood1_col2 = new LayoutTreeNode("12",12,"1","col12",2,5,[],6);  //布局树
    //  layoutTreeNood1.getChildren().push(layoutTreeNood1_col1);
    //  layoutTreeNood1.getChildren().push(layoutTreeNood1_col2);
    //
    // let layoutTreeNood1col2row1 = new LayoutTreeNode("111",111,"11","ttt",1,1,[]);
    // let layoutTreeNood1col2row2 = new LayoutTreeNode("112",112,"11","ttt2",1,1,[]);
    // layoutTreeNood1_col1.getChildren().push(layoutTreeNood1col2row1);
    // layoutTreeNood1_col1.getChildren().push(layoutTreeNood1col2row2);

    const [layoutTree, setLayoutTree] = useState(layoutTreeRoot);
    //元素类型
    const [elementType, setElementType] = useState(-100);

    const [flexGrowVal, setFlexGrowVal] = useState(1);
    const [flexShrinkVal, setFlexShrinkVal] = useState(1);
    const [flexBasisVal, setFlexBasisVal] = useState("auto");
    const [justifyContentVal, setJustifyContentVal] = useState("center");
    const [alignContentVal, setAlignContentVal] = useState("center");

    const [idVal, setIdVal] = useState("-1");


// 编辑flex grow
    const modifyFlex = (id) => {
        //根据info 设置state相关值
        //let _id=info.node.id
        let _id=id
        // 根据id查找节点
        let n=queryNode(layoutTree,_id);
        console.log("n:"+n)
        if(n!=null){
            //setItemId(_id);
            let _flexGrow=n.flexGrow;
            let _flexShrink=n.flexGrow;
            let _flexBasis=n.flexGrow;
            setFlexGrowVal(_flexGrow);
            setFlexShrinkVal(_flexShrink);
            setFlexBasisVal(_flexBasis);
            setIdVal(_id)
            form.setFieldsValue({
                "flexGrowItem":_flexGrow,
                "flexShrinkItem":_flexShrink,
                "flexBasisItem":_flexBasis,
                "idItem": _id
            })
        }else{
            message.error("未查询到对应的节点")
        }
    }
//render dom
    const renderLayout=(nodeObj)=>{
        console.log(nodeObj);
        let ns=nodeObj.children
        let _cells = [];
        let  i=0
        if(ns==null) return '' ;
        for(let node of ns){
            console.log(node);
            if(node.layoutType==1){  //ROW

                        let _flexGrow= node.flexGrow;
                        let _id= node.id;
                        console.log("_flexGrow:"+_flexGrow);
                        let toStr="/main/dynamicForm/formDesigner2/layoutProperty/"+_id
                console.log("toStr:"+_id)

                        _cells.push(<div  id={node.id} style={getRowLayoutStyle(node.flexGrow,node.justifyContent,node.alignContent)} key={i}    onDrop={drop}   onDragOver={allowDrop}>
                                    {/*<div stylelayoutProperty={rowTool}>*/}
                                    <Link to= {toStr} >
                                        <IconFont id="eidtTool"
                                                  style={rowEditTool}
                                                  type="icon-edit"
                                        ></IconFont>
                                    </Link>

                                        <IconFont id="removeTool"
                                                  type="icon-remove"
                                                  style={{display: node.id=="1"? "none": "" ,position:"absolute",top:20,right:1}}
                                                   onClick={()=>removeNode(_id)} ></IconFont>
                                    {/*</div>*/}
                                     {renderLayout(node)}
                                   </div>)

                } else if(node.layoutType==2) {  //COL
                    let _flexGrowForCol= node.flexGrow;
                    let _idForCol= node.id;

                    _cells.push(<div id={node.id}  key={node.id}  style={getColLayoutStyle(node.flexGrow,node.justifyContent,node.alignContent)}   onDrop={drop} onDragOver={allowDrop} >
                        {/*<div style={colTool}>*/}
                            <IconFont id="eidtTool"
                                      style={colEditTool}
                                      type="icon-edit"  onClick={()=>modifyFlex(_idForCol)} ></IconFont>
                            <IconFont id="removeTool" type="icon-remove"  style={colRemoveTool}
                                        onClick={()=>removeNode(_idForCol)} ></IconFont>
                        {/*</div>*/}

                        {/*<div style={this.titleStyle}>col</div>*/}
                        {renderLayout(node)}
                    </div>)
                } else if(node.layoutType==3) {
                _cells.push( <div  style={getTitleStyle()} ><h3>{node.text}</h3></div>)
                };
                i++;
                }
            return  _cells;
        }

    //设置树形节点属性
    const setNodeProperty=(rootNode,currentNode)=>{

        let ns=rootNode.children
        let _cells = [];
        let  i=0
        if(ns==null) return '' ;
        for(let node of ns){
            if(currentNode.id==node.id){  //当前节点
                //进行相关处理
                //node.flexGrow=currentNode.flexGrow
                let _g=node.flexGrow=currentNode.flexGrow
                node.flexGrow=+_g;   //通过+转换为数字
                node.justifyContent=currentNode.justifyContent
                node.alignContent=currentNode.alignContent
                return  ;
            }else{  //判断是否有子节点？  有则进行递归调用
                //判断是否有子节点  如果有子节点 则递归 否则返回
               if(node.children==null ||  node.children.length==0){
                    continue;
               }else{
                   setNodeProperty(node,currentNode)
               }
            }
        }
        return;
    }

    const allowDrop=(event)=>{
        event.preventDefault();
    };
    //根据id查找node
    const  queryNode=(root,nodeId)=>{
        let nodeObj=null;
        // 根节点的情况
        if (nodeId=='0'){
            return  root;
        }
        for(var currentNode of root.children){
            if(nodeId==currentNode.id){  //当前节点
                nodeObj= currentNode;
                break;
            }else{  //判断是否有子节点？  有则进行递归调用
                //判断是否有子节点  如果有子节点 则递归 否则返回
                if(currentNode.children==null ||  currentNode.children.length==0){
                    continue;
                }else{
                    nodeObj=queryNode(currentNode,nodeId)
                    if(nodeObj!=null)  break;
                }
            }
        }
        return nodeObj;
    }


    const quryNodeFromStore=(nodeId)=>{



    }


    function deepCopy(obj1) {
        let _obj = JSON.stringify(obj1);
        let obj2 = JSON.parse(_obj);
        return obj2;
    }

    const IconFont =createFromIconfontCN({
        scriptUrl: '/iconfont.js'
    })

    const myLayout={
        flex: "1 1 0%",
        boxSizing: "border-box",
        display: 'flex',
        flexDirection: 'row',
    }

    const myLayout_1={
        backgroundColor: "#cc99sc"
    }


    // 列布局
    const flex_Col={
        display: 'flex',
        flexDirection: 'row'
    }

    const tool_area={
        flex: "0 0 80px",
        boxSizing: "border-box",
        border:"2px solid #999999",
        margin:"5px",
        padding: "2px",
        display:"flex",
        flexDirection: "column"
    }

    const content_area={
        flex: "1 1 0%",
        padding: "10px",
        boxSizing: "border-box",
        border:"2px solid #999999",
        margin:"5px",
        display:"flex",
        flexDirection:"column"
    }

    const property_area={
        flex: "0 0 150px",

        boxSizing: "border-box"
    }

    const textAlign={
        textAlign:"center"
    }
    // //删除节点
    // 查找本节点 找到parent Node
    // 从父节点child集合当中删除子节点
    const removeNode=(nodeId)=>{
        let rootNodeCopy = deepCopy(layoutTree);

        let n=queryNode(rootNodeCopy,nodeId);
        let _parentId=n.parentId;
        let parentNode=queryNode(rootNodeCopy,_parentId);
        parentNode.children.map((item,index)=>{
            if(item.id==n.id){
                parentNode.children.splice(index,1)
            }
        })
        setLayoutTree(rootNodeCopy)
    }

    const onDrop = (event) => {
        console.log("begin drop:"+event)
         event.dataTransfer.setData('domId', event.currentTarget.id);
        // event.event.dataTransfer.setData('memberId', event.node.id);
    }

//拖放工具栏的图标，放在目标元素上的时候，
    const drop=(event)=>
    {
        let _id=event.currentTarget.id
        // 根据id找到树种的节点
        //给这个节点赋予新的子节点
        let newLayoutTree = deepCopy(layoutTree);
        let n=queryNode(newLayoutTree,_id);
        if(n==null  || n==undefined){
            return;
        }
        if(n.layoutType==null  || n.layoutType==undefined){
            return;
        }
        let newNode=null;
        let _nodeId = newGuid();

        let  _sourceType=event.dataTransfer.getData('domId');


        switch(_sourceType) {
        case "rowIcon": {
            console.log("rowIcon");
            if(!(n.layoutType==1  || n.layoutType==2)){
                return;
            }
            if(n.layoutType==1){
                newNode = new LayoutTreeNode(_nodeId,_nodeId,n.id,_nodeId,2,1,[],"center","center");  //布局树
            }else if(n.layoutType==2){
                newNode = new LayoutTreeNode(_nodeId,_nodeId,n.id,_nodeId,1,1,[],"center","center");  //布局树
            }
            n.children.push({...newNode});
            //设置
            console.log(newLayoutTree)
            break;
        }
        case "title": {
            console.log("title");
            //constructor(id,key,parentId,name,layoutType,size,txt)
            newNode = new TitleNode(_nodeId,_nodeId,n.id,_nodeId,3,3,"標題");
            n.children.push({...newNode});
            //设置
            console.log(newLayoutTree)
            break;
        }
        case "input": {
            console.log("input");
            break;
        }
        case "input1": {
            console.log("input1");
            break;
        }
        case "radio": {
            console.log("radio");
            break;
        }

        case "selectItem": {
            console.log("selectItem");
            break;
        }
        case "mswitch": {
            console.log("mswitch");
            break;
        }
        case "datetimepickerbt": {
            console.log("datetimepickerbt");
            break;
        }
        case "node-tree": {
            console.log("node-tree");
            break;
        }
        case "download": {
            console.log("download");
            break;
        }
        case "image": {
            console.log("image");
            break;
        }
        case "list": {
            console.log("list");
            break;
        }
        case "table": {
            console.log("table");
            break;
        }
        case "tag": {
            console.log("tag");
            break;
        }
        default: {
            console.log("Invalid choice");
            break;
        } }

        setLayoutTree(newLayoutTree);
        stopBubbling(event)
    }




    //stop Bubbling
    const  stopBubbling =(e)=>
    {
        if (e && e.stopPropagation){
            e.stopPropagation()
        }else{
            window.event.cancelBubble=true;
        }
    }


    function newGuid(){
        var guid = "";
        for (var i=1; i<=32; i++){
            var n = Math.floor(Math.random()*16.0).toString(16);
            guid +=   n;
            if((i==8)||(i==12)||(i==16)||(i==20))
                guid += "-";
        }
        return guid+"";
    }

    const FlexItemProperty = () => {

        const onFinish = (values) => {
            console.log('Success:', values);
            let _Itemid=values.idItem;
            let _flexGrow=values.flexGrowItem;
            let _flexShrink=values.flexShrinkItem;
            let _flexBasis=values.flexBasisItem;
            let _justifyContent=values.justifyContent;
            let _alignContent=values.alignContent;
            //找到对应节点 进行设置  根据id 找到所有的已恶点   遍历树 进行设置
            if(values.idItem==='-1'){
                message.info("请选中相应节点")
                return
            }
            let  currentNode=new LayoutTreeNode(_Itemid,-1,-1,"",-1,_flexGrow,[],_justifyContent,_alignContent);
            console.log("test0:"+layoutTree)
            let rootNodeCopy = deepCopy(layoutTree);
            setNodeProperty(rootNodeCopy,currentNode);
            console.log("===================================================="+layoutTreeRoot)
            //setLayoutTree(layoutTreeRoot);
            setLayoutTree(rootNodeCopy);
            console.log("test1:"+layoutTree)
        };

        const onFinishFailed = (errorInfo) => {
            console.log('Failed:', errorInfo);
        };
        const onReset = () => {
            form.resetFields();
        };
        return (
            <Form
                name="basic"
                form={form}
                labelCol={{
                    span: 12,
                }}
                wrapperCol={{
                    span: 12,
                }}
                initialValues={{
                    idItem:idVal,
                    flexGrowItem:flexGrowVal,
                    flexShrinkItem:flexShrinkVal,
                    flexBasisItem:flexBasisVal,
                    justifyContent:justifyContentVal,
                    alignContent:alignContentVal
                }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
            >

                <Form.Item
                    label="id"
                    name="idItem"
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="grow"
                    name="flexGrowItem"
                    rules={[
                        {
                            required: true,
                            message: 'Please input the flex-grow!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>


                <Form.Item
                    label="Shrink"
                    name="flexShrinkItem"
                    rules={[
                        {
                            required: true,
                            message: 'Please input the flex-shrink!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="basis"
                    name="flexBasisItem"
                    rules={[
                        {
                            required: true,
                            message: 'Please input flex-basis!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="justify-Content"
                    name="justifyContent"
                    rules={[
                        {
                            required: true,
                            message: 'Please input justify-Content!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="align-Content"
                    name="alignContent"
                    rules={[
                        {
                            required: true,
                            message: 'Please input align-Content!',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    wrapperCol={{
                        offset: 8,
                        span: 16,
                    }}
                >
                    <Button type="primary" htmlType="submit">
                        Submit
                    </Button>

                    {/*<Button htmlType="button" onClick={onReset}>*/}
                    {/*Reset*/}
                    {/*</Button>*/}

                </Form.Item>
            </Form>
        );
    }
        return (
            <div style={myLayout}>
                <div style={ tool_area }>
                    <PageHeader
                        className="site-page-header"
                         title="工具"
                    />
                    <div style={textAlign}>


                    <IconFont id="rowIcon" type="icon-rows"  onDragStart={onDrop}   draggable="true"></IconFont>
                    </div>

                    {/*<div style={textAlign}>*/}
                    {/*    <IconFont id="colIcon" type="icon-column" onDragStart={onDrop}   draggable="true"></IconFont>*/}
                    {/*</div>*/}
                    <div style={textAlign}>
                        <IconFont id="title" type="icon-title"
                                  draggable="true"
                                  onDragStart={onDrop} ></IconFont>
                    </div>

                    <div style={textAlign}>
                        <IconFont id="input" type="icon-input"
                                  draggable="true"
                                  onDragStart={onDrop} ></IconFont>
                    </div>


                    <div style={textAlign}>
                        <IconFont id="input1" type="icon-input1"
                                  draggable="true"
                                  onDragStart={onDrop}></IconFont>
                    </div>


                    <div style={textAlign}>
                        <IconFont id="radio" type="icon-radiobox"
                                  draggable="true"
                                  onDragStart={onDrop}></IconFont>
                    </div>

                    <div style={textAlign}>
                        <IconFont id="selectItem"
                                  onDragStart={onDrop}
                                  draggable="true"
                                  type="icon-light-component-automation-selectItem"></IconFont>
                    </div>


                    {/*<div style={textAlign}>*/}
                    {/*    <IconFont id="multiselect" type="icon-icon-Multiselect"></IconFont>*/}
                    {/*</div>*/}

                    <div style={textAlign}>
                        <IconFont id="mswitch" type="icon-mswitch"
                                  draggable="true"
                                  onDragStart={onDrop}></IconFont>
                    </div>

                    <div style={textAlign}>
                        <IconFont id="datetimepickerbt" type="icon-datetimepickerbt_back"
                                  draggable="true"
                                  onDragStart={onDrop}></IconFont>
                    </div>

                    <div style={textAlign}>
                        <IconFont id="node-tree" type="icon-node-tree"
                                  draggable="true"
                                  onDragStart={onDrop}></IconFont>
                    </div>

                    <div style={textAlign}>
                        <IconFont id="download" type="icon-download"
                                  draggable="true"
                                  onDragStart={onDrop}></IconFont>
                    </div>

                    <div style={textAlign}>
                        <IconFont id="image" type="icon-image"
                                  draggable="true"
                                  onDragStart={onDrop}></IconFont>
                    </div>

                    <div style={textAlign}>
                        <IconFont id="list" type="icon-list"
                                  draggable="true"
                                  onDragStart={onDrop}></IconFont>
                    </div>

                    <div style={textAlign}>
                        <IconFont id="table" type="icon-table"
                                  draggable="true"
                                  onDragStart={onDrop}></IconFont>
                    </div>

                    <div style={textAlign}>
                        <IconFont id="tag" type="icon-tag"
                                  draggable="true"
                                  onDragStart={onDrop}></IconFont>
                    </div>
                </div>

                {/*画板*/}
                <div id = '0'   style={ content_area }    onDrop={drop}   onDragOver={allowDrop}>
                    {renderLayout(layoutTree)}
                </div>
                <div style={ property_area }>
                    <Switch>
                        <Route path="/main/dynamicForm/formDesigner2/category">
                            <Category />
                        </Route>
                        <Route path="/main/dynamicForm/formDesigner2/layoutProperty/:itemId">
                            <LayoutProperty />
                        </Route>
                        <Route path="/main/dynamicForm/formDesigner2/titleProperty">
                            <TitleProperty />
                        </Route>
                        <Route path="/main/dynamicForm/formDesigner2/inputProperty">
                            <InputProperty />
                        </Route>
                    </Switch>
                    {/*{FlexItemProperty()}*/}

                </div>
            </div>
        )
}

//type  0 是根  1 是row  2 是col
class LayoutTreeNode{
    constructor(id,key,parentId,name,layoutType,flexGrow,children,justifyContentVal,alignContentVal)
    {
        this.id=id;  // 数值
        this.key=key;  // 数值
        this.parentId=parentId;  // 数值
        this.name=name;
        this.layoutType=layoutType;
        this.children=children;  // 用数组的方式保存子节点，适合更多业务场景
        //this.flexValue="1 1 auto";
        this.flexGrow=flexGrow;
        this.justifyContent=justifyContentVal;
        this.alignContent=alignContentVal;
        // this.colSpan=colSpan;
        // this.position=position;
    }

    setId(id){
        this.id=id;
    }
    getId(){
        return this.id
    }
    getKey(){
        return this.key
    }
    getName(){
        return this.name
    }
    getParentId(){
        return this.parentId
    }
    getLayoutType(){
        return this.layoutType
    }
    getChildren(){
        return this.children
    }
    getFlexGrow(){
        return this.flexGrow
    }
}

//h1...h5
class TitleNode{
    constructor(id,key,parentId,name,layoutType,size,txt)
    {
        this.id=id;  // 数值
        this.key=key;  // 数值
        this.parentId=parentId;  // 数值
        this.name=name;
        this.layoutType=layoutType;
        this.size=size;
        this.text=txt
    }

    setId(id){
        this.id=id;
    }
    getId(){
        return this.id
    }
    getKey(){
        return this.key
    }
    getName(){
        return this.name
    }
    getParentId(){
        return this.parentId
    }
    getLayoutType(){
        return this.layoutType
    }
    getChildren(){
        return this.children
    }
}


class InputNode{
    constructor(id,key,parentId,name,layoutType,txt)
    {
        this.id=id;  // 数值
        this.key=key;  // 数值
        this.parentId=parentId;  // 数值
        this.name=name;
        this.layoutType=layoutType;
        this.text=txt
    }

    setId(id){
        this.id=id;
    }
    getId(){
        return this.id
    }
    getKey(){
        return this.key
    }
    getName(){
        return this.name
    }
    getParentId(){
        return this.parentId
    }
    getLayoutType(){
        return this.layoutType
    }
    getChildren(){
        return this.children
    }
}





